import 'dart:ui';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:my_shop/cache_event_identification.dart';
import 'package:my_shop/load_my_goods.dart';
import 'package:my_shop/widget/buy_button_widget.dart';

class SlidingGoodListItemPage extends StatefulWidget {
  const SlidingGoodListItemPage(this.model, this.isFirst, this.jumpMyPage,
      {Key? key})
      : super(key: key);

  final GoodModel model;

  final bool isFirst;

  final Function jumpMyPage;

  @override
  State<SlidingGoodListItemPage> createState() =>
      _SlidingGoodListItemPageState();
}

class _SlidingGoodListItemPageState extends State<SlidingGoodListItemPage>
    with SingleTickerProviderStateMixin {
  AnimationController? _controller;

  @override
  void initState() {
    super.initState();

    /// Add slip-up tips only on the first page
    if (widget.isFirst) {
      _controller = AnimationController(
        vsync: this,
        duration: const Duration(seconds: 1),
      )..repeat();
    }
  }

  @override
  void dispose() {
    if (widget.isFirst) {
      _controller?.dispose();
    }
    super.dispose();
  }

  Widget buildArrow(double offsetY) {
    return AnimatedBuilder(
      animation: _controller!,
      builder: (context, child) {
        return Opacity(
          opacity: 1.0 - _controller!.value,
          child: Transform.translate(
            offset: Offset(0.0, -40.0 * _controller!.value),
            child: Icon(
              Icons.keyboard_arrow_up,
              color: Colors.grey.withOpacity(0.5),
              size: 80.0,
            ),
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Scaffold(
          body: Container(
            color: Colors.grey,
            child: ClipRRect(
              borderRadius: const BorderRadius.all(Radius.circular(8)),
              child: Column(
                children: [
                  Expanded(
                    child: Stack(
                      children: [
                        Positioned.fill(
                          child: ImageFiltered(
                            imageFilter:
                                ImageFilter.blur(sigmaX: 10, sigmaY: 10),
                            child: Image.asset(
                              widget.model.localUrl ?? '',
                              fit: BoxFit.fill,
                            ),
                          ),
                        ),
                        Center(
                          child: Image.asset(
                            widget.model.localUrl ?? '',
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
          bottomNavigationBar: Container(
            color: Colors.grey,
            height: 84 + ScreenUtil.getBottomBarH(context),
          ),
        ),
        Positioned.fill(
          child: Container(
            padding: const EdgeInsets.all(16),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Row(
                  children: [
                    Expanded(
                      child: _detailInfo(),
                    ),
                  ],
                ),
                const SizedBox(
                  height: 8,
                ),
                Row(
                  children: [
                    Expanded(
                      child: BuyButton(
                        gradient: const LinearGradient(
                          colors: [
                            Color(0xFFFFAF37),
                            Color(0xFFFC9318),
                          ],
                        ),
                        unSelectedGradient: const LinearGradient(
                          colors: [
                            Color(0xFFFFD28D),
                            Color(0xFFFFC786),
                          ],
                        ),
                        onPressed: (widget.model.stock ?? 0) > 0
                            ? () {
                                if (!(SpUtil.getBool(Constant.isLoginStatus) ??
                                    false)) {
                                  Navigator.pop(context);
                                  widget.jumpMyPage.call();
                                  Fluttertoast.showToast(
                                      msg:
                                          'Currently out of the login state, please login and try again');

                                  return;
                                }
                                Fluttertoast.showToast(
                                    msg: 'add to cart success');

                                /// See if the item is in the cache shopping cart list
                                bool thisGoodInCache = false;
                                List<GoodModel>? tempList =
                                    SpUtil.getObjList<GoodModel>(
                                        Constant.cartModelList, (v) {
                                  return GoodModel.fromJson(
                                      v as Map<String, dynamic>);
                                });
                                if (tempList?.isNotEmpty == true) {
                                  for (int i = 0; i < tempList!.length; i++) {
                                    if (tempList[i].goodId ==
                                        widget.model.goodId) {
                                      thisGoodInCache = true;
                                      tempList[i].num =
                                          (tempList[i].num ?? 0) + 1;
                                      SpUtil.putObjectList(
                                          Constant.cartModelList, tempList);
                                      return;
                                    }
                                  }
                                  if (!thisGoodInCache) {
                                    GoodModel tempModel = widget.model;
                                    tempModel.num = 1;
                                    tempList.add(tempModel);
                                    SpUtil.putObjectList(
                                        Constant.cartModelList, tempList);
                                  }
                                } else {
                                  GoodModel tempModel = widget.model;
                                  tempModel.num = 1;
                                  SpUtil.putObjectList(
                                      Constant.cartModelList, [tempModel]);
                                }
                              }
                            : null,
                        minWidth: 110,
                        text: 'Add to Cart',
                      ),
                    ),
                    Expanded(
                      child: BuyButton(
                        onPressed: (widget.model.stock ?? 0) > 0
                            ? () {
                                if (!(SpUtil.getBool(Constant.isLoginStatus) ??
                                    false)) {
                                  Navigator.pop(context);
                                  widget.jumpMyPage.call();
                                  Fluttertoast.showToast(
                                      msg:
                                          'Currently out of the login state, please login and try again');
                                  return;
                                }
                                Fluttertoast.showToast(msg: 'buy success');
                                List<GoodModel> allGoodsList =
                                    SpUtil.getObjList<GoodModel>(
                                            Constant.allGoodsList,
                                            (v) => GoodModel.fromJson(
                                                v as Map<String, dynamic>)) ??
                                        [];
                                for (int i = 0; i < allGoodsList.length; i++) {
                                  if (allGoodsList[i].goodId ==
                                      widget.model.goodId) {
                                    setState(() {
                                      widget.model.stock =
                                          (widget.model.stock ?? 0) - 1;
                                      allGoodsList[i].stock =
                                          (allGoodsList[i].stock ?? 0) - 1;
                                      SpUtil.putObjectList(
                                          Constant.allGoodsList, allGoodsList);
                                    });
                                  }
                                }
                                List<OrderModel> orderList =
                                    SpUtil.getObjList<OrderModel>(
                                            Constant.orderList,
                                            (v) => OrderModel.fromJson(
                                                v as Map<String, dynamic>)) ??
                                        [];
                                GoodModel orderGoodModel = widget.model;
                                orderGoodModel.num = 1;
                                OrderModel tempModel = OrderModel(
                                  orderId: orderList.isEmpty
                                      ? 1
                                      : orderList.last.orderId! + 1,
                                  orderNo: orderList.isEmpty
                                      ? '000001'
                                      : getOrderNo(orderList.last.orderNo!),
                                  createTime: DateTime.now().toString(),
                                  totalPrice: orderGoodModel.price,
                                  goodList: [orderGoodModel],
                                );
                                if (orderList.isEmpty) {
                                  orderList = [tempModel];
                                } else {
                                  orderList.add(tempModel);
                                }
                                SpUtil.putObjectList(
                                    Constant.orderList, orderList);
                              }
                            : null,
                        minWidth: 110,
                        leftOrRight: false,
                        text: 'Buy Now',
                      ),
                    ),
                  ],
                )
              ],
            ),
          ),
        )
      ],
    );
  }

  Widget _detailInfo() {
    return Stack(
      children: [
        Container(
            padding: const EdgeInsets.all(16),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(8), color: Colors.white),
            child: buildDetailInfo()),
        if (widget.isFirst) ...[
          Positioned(
              top: 40,
              left: ScreenUtil.getScreenW(context) / 2 - 40 - 16,
              child: buildArrow(0.0)),
          Positioned(
              top: 60,
              left: ScreenUtil.getScreenW(context) / 2 - 40 - 16,
              child: buildArrow(1.0)),
        ]
      ],
    );
  }

  Widget buildDetailInfo() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          crossAxisAlignment: CrossAxisAlignment.baseline,
          textBaseline: TextBaseline.alphabetic,
          children: [
            const Text(
              r'$',
              style: TextStyle(
                fontSize: 12,
                color: Color(0xFFFF6914),
                fontWeight: FontWeight.bold,
              ),
              overflow: TextOverflow.ellipsis,
            ),
            Text(
              (widget.model.price ?? '').toString(),
              style: const TextStyle(
                fontSize: 24,
                color: Color(0xFFFF6914),
                fontWeight: FontWeight.bold,
              ),
              overflow: TextOverflow.ellipsis,
            ),
            const SizedBox(
              width: 5,
            ),
            Offstage(
              offstage: widget.model.marketPrice == null,
              child: Text(
                (widget.model.marketPrice ?? '').toString(),
                style: const TextStyle(
                    fontSize: 12,
                    color: Color(0xFFAAB0B2),
                    decoration: TextDecoration.lineThrough),
                overflow: TextOverflow.ellipsis,
              ),
            ),
            Expanded(child: Container()),
            Text(
              'In Stock:${((widget.model.stock ?? 0) < 0) ? 0 : widget.model.stock ?? 0}',
              style: const TextStyle(color: Color(0xFFC4C4C4)),
            )
          ],
        ),
        const SizedBox(
          height: 8,
        ),
        SizedBox(
          child: Text(
            widget.model.goodName ?? '',
            style: const TextStyle(
                fontSize: 16,
                color: Color(0xFF333333),
                fontWeight: FontWeight.bold),
          ),
        ),
        const SizedBox(
          height: 16,
        ),
      ],
    );
  }

  String getOrderNo(String lastNo) {
    int lastNoToInt = int.parse(lastNo) + 1;
    switch (lastNoToInt.toString().length) {
      case 1:
        return '00000$lastNoToInt';
      case 2:
        return '0000$lastNoToInt';
      case 3:
        return '000$lastNoToInt';
      case 4:
        return '00$lastNoToInt';
      case 5:
        return '0$lastNoToInt';
      default:
        return '$lastNoToInt';
    }
  }
}
